package com.sky.controller.common;

import com.alisms.config.AlismsTemplate;
import com.sky.pojo.ShortUrl;
import com.sky.result.Result;
import com.sky.service.common.CommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private CommonService commonService;

    @ApiOperation("上传文件")
    @PostMapping("/admin/common/upload")
    public Result<String> upload(MultipartFile file){

        return commonService.upload(file);
    }


    @Autowired
    private AlismsTemplate alismsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("短信发送")
    @GetMapping("/courier/validateCodeToPhone")
    public Result<String> sendMessage(String telephone){

        String code = "";
        Random random = new Random();
        for(int i=0;i<4;i++){
            code+=random.nextInt(10);
        }

        //发送短信
//        try {
//            alismsTemplate.sendMessage(telephone,code);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new AliMessageException("阿里云短信发送异常");
//        }
        //将验证码存入到redis中
        redisTemplate.opsForValue().set("code:"+telephone,code,300, TimeUnit.SECONDS);

        return Result.success(code);
    }


    @GetMapping("/dispatch/loadRouteInfo")
    @ApiOperation("加载地图的线路信息")
    public Result<String> loadRouteInfo(Long tradeNo,Long courierId){

        return commonService.loadRouteInfo(tradeNo,courierId);
    }


    @ApiOperation("短信中短链访问接口")
    @GetMapping("/r/{code}")
    public void shortUrl(@PathVariable("code") String code, HttpServletResponse response) throws Exception{

        //查询短链
       ShortUrl shortUrl = commonService.getShortUrl(code);

       //重定向
       response.sendRedirect(shortUrl.getFullUrl());
    }
}
